/*
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.megagoodsoftware.MediaShare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.megagoodsoftware.smugmug.AlbumComparator;
import com.megagoodsoftware.smugmug.Constants;
import com.megagoodsoftware.smugmug.SmugMug;
import com.megagoodsoftware.smugmug.SmugMugAlbum;

/**
 * Activity used to display a Flickr user's photostream. This activity shows a fixed
 * number of photos at a time. The activity is invoked either by LoginActivity, when
 * the application is launched normally, or by a Home shortcut, or by an Intent with
 * the view action and a flickr://photos/nsid URI.
 */
public class PickAlbumActivity extends ListActivity        {

    static final String ACTION = "com.megagoodsoftware.MediaShare.SMUGMUG_PICK_ALBUM";

    static final String EXTRA_NOTIFICATION = "com.megagoodsoftware.MediaShare.extra_notify_id";
    static final String EXTRA_NSID = "com.megagoodsoftware.MediaShare.extra_nsid";

    private static final String STATE_USER = "com.megagoodsoftware.MediaShare.state_user";
    private static final String STATE_PAGE = "com.megagoodsoftware.MediaShare.state_page";
    private static final String STATE_PAGE_COUNT = "com.megagoodsoftware.MediaShare.state_pagecount";
    private static final String STATE_ALBUM = "com.megagoodsoftware.MediaShare.state_album";

    private User mUser;
    private int mCurrentPage = 1;
    private int mPageCount = 0;

    private AsyncTask<?, ?, ?> mTask;
    private String mUsername;
	private SmugMug sm;
	private ArrayList<SmugMugAlbum> mAlbums;
	private ArrayAdapter<String> mAdapter;
	private SmugMugAlbum mAlbum;
    private String[] mAlbumArray;
	private boolean mIsUploading = false;
	public SmugMug GetSmugMugHandle() {
		return sm;
	}
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//		setContentView(R.layout.pick_album);

        clearNotification();

        // Try to find a user name in the saved instance state or the intent
        // that launched the activity. If no valid user NSID can be found, we
        // just close the activity.
        if (!initialize(savedInstanceState)) {
            finish();
            return;
        }
        sm = ((MediaShareApp) getApplicationContext()).getSmugMugHandle();
        
        getListView().setTextFilterEnabled(true);

        if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
			mIsUploading  = true;
		}

      	mTask = new GetAlbumListTask().execute();
    }

	private void showAlbumList() {
		mAdapter = new ArrayAdapter<String>(this,
			android.R.layout.simple_list_item_1,
			mAlbumArray);
	setListAdapter(mAdapter);
}
    /**
    * @see android.app.Activity#onCreateDialog(int)
    */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		case 0: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("Fetching your albums...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

    protected void gotoNextActivity() {
    	if (mIsUploading) {
    		MediaShareActivity.show(this,mAlbum.getTitle());
    	} else
    		SmugMugPhotostreamActivity.show(this, mAlbum.getTitle());
    	
    	mIsUploading = false; //when user clicks back to here,they can view the album
	}
	private void clearNotification() {
        final int notification = getIntent().getIntExtra(EXTRA_NOTIFICATION, -1);
        if (notification != -1) {
            NotificationManager manager = (NotificationManager)
                    getSystemService(Context.NOTIFICATION_SERVICE);
            manager.cancel(notification);
        }
    }

    /**
     * Starts the PhotostreamActivity for the specified user.
     *
     * @param context The application's environment.
     * @param user The user whose photos to display with a PhotostreamActivity.
     */
    static void show(Context context, User user) {
        final Intent intent = new Intent(ACTION);
		intent.putExtras(((Activity) context).getIntent());
        intent.putExtra(SmugMugBundleHelper.EXTRA_USER, user);
        context.startActivity(intent);
    }

    /**
     * Restores a previously saved state or, if missing, finds the user's NSID
     * from the intent used to start the activity.
     *
     * @param savedInstanceState The saved state, if any.
     *
     * @return true if a {@link com.google.android.photostream.Flickr.User} was
     *         found either in the saved state or the intent.
     */
    private boolean initialize(Bundle savedInstanceState) {
        User user;
        if (savedInstanceState != null) {
            user = savedInstanceState.getParcelable(STATE_USER);
            mCurrentPage = savedInstanceState.getInt(STATE_PAGE);
            mPageCount = savedInstanceState.getInt(STATE_PAGE_COUNT);
            mAlbum = savedInstanceState.getParcelable(STATE_ALBUM);
        } else {
            final Intent intent = getIntent();
            user = SmugMugBundleHelper.getUserFromBundle(intent);
        }
        mUser = user;
        return mUser != null || mUsername != null;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable(STATE_USER, mUser);
        outState.putInt(STATE_PAGE, mCurrentPage);
        outState.putInt(STATE_PAGE_COUNT, mPageCount);
        outState.putParcelable(STATE_ALBUM, mAlbum);
        removeDialog(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
            mTask.cancel(true);
        }
    }

	public void onListItemClick(ListView parent, View v,
			int position, long id) {
		mAlbum = mAlbums.get(position);
		//Toast.makeText(getApplicationContext(), "Using album " + mAlbum.getTitle(), Toast.LENGTH_SHORT).show();
		gotoNextActivity();
		//selection.setText(mAlbumArray[position]);
	}

    /**
     * Background task used to load the list of photos. The tasks queries Flickr for the
     * list of photos to display and ends by starting the LoadPhotosTask.
     */
    private class GetAlbumListTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        public void onPreExecute() {
			showDialog(0);
        }

        public Boolean doInBackground(Void... params) {
    		try {
//    			sm.loginWithHash(Integer.parseInt(mUser.getId()), 
//    											  mUser.getPassword());
//    			Log.i(Constants.TAG, sm.getAccount().toString()); 
//    			
//    			sm.updateCache();
    			mAlbums = sm.getAlbums();
    			Collections.sort(mAlbums, new AlbumComparator());
    			mAlbumArray = new String[mAlbums.size()];

    			int x = 0;
    			for (Iterator<SmugMugAlbum> it = mAlbums.iterator(); it
    					.hasNext();) {
    				mAlbumArray[x] = it.next().getTitle();
    				x++;
    			}
     		} catch (NumberFormatException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return true;
        }

        @Override
        public void onPostExecute(Boolean input) {
        	try {
        		dismissDialog(0);
        	} catch (Exception e) {
        		
        	}
            if (mAlbums == null) {
            	//This is bad
    			Log.i(Constants.TAG, "PickAlbum, mAlbums = null!"); 
				Toast.makeText(getApplicationContext(), "Problem connecting to SmugMug, please try again", Toast.LENGTH_LONG).show();
				finish();
           } else if (mAlbum == null) {
    			Log.i(Constants.TAG, "PickAlbum, mAlbum = null"); 
            	//showDialog(1);
    			showAlbumList();
            } else {
    			Log.i(Constants.TAG, "PickAlbum, mAlbum != null, never expected to get here!"); 
    			showAlbumList();
            }
            mTask = null;
        }
    }

}
